import re

from util.equation import Equation
from util.add_equation import AddEquation
from util.sub_equation import SubEquation


def parse(equation: str):
    rs = None
    equation = re.sub(r"[^0-9+-=]|/", "", equation)
    if re.match(r"\d+[+-]{1}\d+={1}\d*", equation):
        if "+" in equation:
            pattern = r'(\d+)\+(\d+)=(\d*)'
            match = re.search(pattern, equation)
            if match:
                # 提取数字
                left = match.group(1)
                right = match.group(2)
                rs = match.group(3) or None
                obj = AddEquation()
                obj.left = int(left)
                obj.right = int(right)

        elif "-" in equation:
            pattern = r'(\d+)\-(\d+)=(\d*)'
            match = re.search(pattern, equation)
            if match:
                # 提取数字
                left = match.group(1)
                right = match.group(2)
                rs = match.group(3) or None
                obj = SubEquation()
                obj.left = int(left)
                obj.right = int(right)
        else:
            obj = Equation(0, 0, "错误格式")
    else:
        obj = Equation(0, 0, "错误格式")

    if rs is not None:
        rs = int(rs)
    return obj, rs
